/* 
**                         _______
**   ____________ _______ _\__   /_________       ___  _____
**  |    _   _   \   _   |   ____\   _    /      |   |/  _  \
**  |    /   /   /   /   |  |     |  /___/   _   |   |   /  /
**  |___/___/   /___/____|________|___   |  |_|  |___|_____/
**          \__/                     |___|
**  
**
** (c) 2009 Wijnand 'maze' Modderman - http://maze.io/
**
*/

/*
Script: Validator.js
  Simple form validation for MooTools <http://mootools.net>.

License:
  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.

Authors:
  Wijnand Modderman <javascript@maze.io>
*/

var Validator = new Class({
  Implements: [Options],

  options: {
    message:  'This field is invalid.',
    validate:  function(text) { return true; }
  },

  initialize: function(el, options) {
    console.log('validate', el);
    this.el = el;
    this.setOptions(options);
    this.validate();
    console.log(this.el.get('name'), 'is', this.valid ? '' : 'NOT', 'valid');
  },

  getValue: function() {
    switch (this.el.get('tag')) {
      case 'input':
        var type = this.el.get('type');
        switch (this.el.get('type')) {
          case 'checkbox':
            return this.el.get('checked');
          case 'hidden':
          case 'password':
          case 'text':
            return this.el.get('value');
          case 'radio':
            console.log(this.el.get('value'));
            break;
        }
        break;
      case 'select':
        return this.el.get('value');
      case 'textarea':
        return this.el.get('value');
    }
  },

  validate: function() {
    this.valid = this.options.validate(this.getValue()); 
    this.error = this.valid ? null : this.options.message;
  }
});

// Simple validator
Validator.Required = new Class({
  Extends: Validator,
  options: {
    message:   'This field is required.',
    validate:  function(text) { return !!text; }
  }
});

// Number (also float) validator
Validator.Number = new Class({
  Extends: Validator,
  options: {
    message:  'This is not a valid number.',
    validate: function(text) { return !isNaN((+text)); }
  }
});

// Integer validator
Validator.Integer = new Class({
  Extends: Validator,
  options: {
    message:  'This is not a valid integer.',
    validate: function(text) { return !isNaN((+text)) && ((+text) % 1 == 0); }
  }
});

// E-mail validator (RFC 2822)
Validator.Email = new Class({
  Extends: Validator,
  options: {
    message:  'This is not a valid e-mail address.',
    validate: function(text) { return !text || /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(text); }
  }
});

// URL validator
Validator.Url = new Class({
  Extends: Validator,
  options: {
    message:  'This is not a valid URL.',
    validate: function(text) { return !text || /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/.test(text); }
  }
});

var FormValidator = new Class({
  Implements: [Options, Events],

  options: {
    selector:   'input, select, textarea',
    prefix:     'field-',
    seperator:  '-',
    validators: {
      'required': Validator.Required,
      'number':   Validator.Number,
      'integer':  Validator.Integer,
      'float':    Validator.Number,
      'email':    Validator.Email,
      'url':      Validator.Url
    }
  },

  initialize: function(el, options) {
    this.setOptions(options);
    this.el = $(el);

    // thanks cpojer
    var self = this;
    this.fire = function(e) {
      try {
      self.fireEvent(e.type)[e.type].apply(self, [e, this]);
      } catch (error) { console.warn(error); }
    };
    this.el.set('events', {'submit': this.fire});
    this.attach(this.options.selector);
  },

  attach: function(selector) {
    var classFilter = new RegExp('^' + this.options.prefix + '(.*)');
    this.validator = $H({});
    this.fields    = this.el.getElements(selector);
    this.fields.each(function(el) {
      var name = el.get('name');
      if (!name) return;
      if (!this.validator.has(name)) this.validator[name] = []
      $A(el.get('class').split(' ')).each(function(klass) {
        var match = classFilter.exec(klass);
        if (match && match[1].split(this.options.seperator)[0] in this.options.validators) {
          var match = match[1].split(this.options.seperator);
          var check = match.pop(0);
          this.validator[name].include({el: el, validator: this.options.validators[check], options: match});
        }
      }, this);
    }, this);
  },

  check: function() {
    var errors = $H({});
    this.validator.each(function(checks, name) {
      if (!errors.has(name)) errors[name] = [];
      checks.each(function(check) {
        var field = new check.validator(check.el);
        if (!field.valid) errors[name].include(field.error);
      }, this);
      if (!errors[name].length) delete errors[name];
    }, this);
    return errors;
  },

  // Events

  error: function(e, errors) {
    console.log('onError', e, errors);
  },

  submit: function(e) {
    this.fireEvent('submit', [e, this]);
    if (errors = this.check()) {
      e.stop();
      this.$events && 'error' in this.$events ? this.fireEvent('error', [e, errors]) : this.error(e, errors);
    }
  }
});


